<template>
  <div class="statistics-overview">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>总销售额</span>
              <el-tag size="small" type="success">月同比 +12%</el-tag>
            </div>
          </template>
          <div class="card-body">
            <div class="amount">¥{{ formatNumber(overviewData.totalSales) }}</div>
            <div class="trend">
              <span>日销售额</span>
              <span class="value">¥{{ formatNumber(overviewData.dailySales) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>订单总数</span>
              <el-tag size="small" type="success">月同比 +8%</el-tag>
            </div>
          </template>
          <div class="card-body">
            <div class="amount">{{ formatNumber(overviewData.totalOrders) }}</div>
            <div class="trend">
              <span>日订单数</span>
              <span class="value">{{ formatNumber(overviewData.dailyOrders) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>会员总数</span>
              <el-tag size="small" type="success">月同比 +15%</el-tag>
            </div>
          </template>
          <div class="card-body">
            <div class="amount">{{ formatNumber(overviewData.totalMembers) }}</div>
            <div class="trend">
              <span>新增会员</span>
              <span class="value">{{ formatNumber(overviewData.newMembers) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>商品总数</span>
              <el-tag size="small" type="success">月同比 +5%</el-tag>
            </div>
          </template>
          <div class="card-body">
            <div class="amount">{{ formatNumber(overviewData.totalProducts) }}</div>
            <div class="trend">
              <span>新增商品</span>
              <span class="value">{{ formatNumber(overviewData.newProducts) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销售趋势图 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>销售趋势</span>
          <el-radio-group v-model="salesTrendType" size="small">
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="year">本年</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div class="chart-container">
        <v-chart class="chart" :option="salesTrendOption" autoresize />
      </div>
    </el-card>

    <!-- 订单分布和商品排行 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="orderStatusOption" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>商品销售排行</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="productRankingOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 会员消费分布 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>会员消费分布</span>
        </div>
      </template>
      <div class="chart-container">
        <v-chart class="chart" :option="memberConsumptionOption" autoresize />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  getDashboardStatistics,
  getSalesTrend,
  getOrderStatusDistribution,
  getProductRanking,
  getCustomerConsumption
} from '@/api/merchant'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

// 数据概览
const overviewData = ref({
  totalSales: 0,
  dailySales: 0,
  totalOrders: 0,
  dailyOrders: 0,
  totalMembers: 0,
  newMembers: 0,
  totalProducts: 0,
  newProducts: 0
})

// 销售趋势类型
const salesTrendType = ref('week')

// 销售趋势数据
const salesTrendData = ref({
  dates: [],
  sales: [],
  orders: []
})

// 订单状态分布数据
const orderStatusData = ref([])

// 商品销售排行数据
const productRankingData = ref([])

// 会员消费分布数据
const memberConsumptionData = ref([])

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 销售趋势图表配置
const salesTrendOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  legend: {
    data: ['销售额', '订单数']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: salesTrendData.value.dates
  },
  yAxis: [
    {
      type: 'value',
      name: '销售额',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    {
      type: 'value',
      name: '订单数',
      position: 'right'
    }
  ],
  series: [
    {
      name: '销售额',
      type: 'line',
      smooth: true,
      data: salesTrendData.value.sales,
      itemStyle: {
        color: '#409EFF'
      }
    },
    {
      name: '订单数',
      type: 'line',
      smooth: true,
      yAxisIndex: 1,
      data: salesTrendData.value.orders,
      itemStyle: {
        color: '#67C23A'
      }
    }
  ]
}))

// 订单状态分布图表配置
const orderStatusOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      data: orderStatusData.value,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))

// 商品销售排行图表配置
const productRankingOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value'
  },
  yAxis: {
    type: 'category',
    data: productRankingData.value.map(item => item.name)
  },
  series: [
    {
      name: '销售额',
      type: 'bar',
      data: productRankingData.value.map(item => item.sales),
      itemStyle: {
        color: '#409EFF'
      }
    }
  ]
}))

// 会员消费分布图表配置
const memberConsumptionOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: memberConsumptionData.value.map(item => item.range)
  },
  yAxis: {
    type: 'value',
    name: '会员数'
  },
  series: [
    {
      name: '会员数',
      type: 'bar',
      data: memberConsumptionData.value.map(item => item.count),
      itemStyle: {
        color: '#67C23A'
      }
    }
  ]
}))

// 获取数据概览
const getOverviewData = async () => {
  try {
    const res = await getDashboardStatistics()
    overviewData.value = res.data
  } catch (error) {
    console.error('获取数据概览失败:', error)
  }
}

// 获取销售趋势数据
const getSalesTrendData = async () => {
  try {
    const res = await getSalesTrend({ type: salesTrendType.value })
    salesTrendData.value = res.data
  } catch (error) {
    console.error('获取销售趋势数据失败:', error)
  }
}

// 获取订单状态分布数据
const getOrderStatusData = async () => {
  try {
    const res = await getOrderStatusDistribution()
    orderStatusData.value = res.data
  } catch (error) {
    console.error('获取订单状态分布数据失败:', error)
  }
}

// 获取商品销售排行数据
const getProductRankingData = async () => {
  try {
    const res = await getProductRanking()
    productRankingData.value = res.data
  } catch (error) {
    console.error('获取商品销售排行数据失败:', error)
  }
}

// 获取会员消费分布数据
const getMemberConsumptionData = async () => {
  try {
    const res = await getCustomerConsumption()
    memberConsumptionData.value = res.data
  } catch (error) {
    console.error('获取会员消费分布数据失败:', error)
  }
}

// 监听销售趋势类型变化
watch(salesTrendType, () => {
  getSalesTrendData()
})

onMounted(() => {
  getOverviewData()
  getSalesTrendData()
  getOrderStatusData()
  getProductRankingData()
  getMemberConsumptionData()
})
</script>

<style lang="scss" scoped>
.statistics-overview {
  padding: 20px;

  .data-overview {
    margin-bottom: 20px;
  }

  .data-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-body {
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin: 10px 0;
      }

      .trend {
        font-size: 14px;
        color: #909399;

        .value {
          margin-left: 8px;
          color: #67C23A;
        }
      }
    }
  }

  .chart-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 400px;

      .chart {
        height: 100%;
      }
    }
  }

  .chart-row {
    margin-bottom: 20px;
  }
}
</style> 